﻿// owner 蒋家伟

#include "ElementChangedHandler.h"

//std
#include <iostream>
#include <string>

// jsdk
#include "IElementChangedEvent.h"
#include "IElementChangedEventArgs.h"
#include "IDocument.h"
#include "IElementBasicInfomation.h"
#include "IElement.h"
#include "Dbg_Warn_Define.h"

using namespace jsdk;

namespace
{
    static jsdk::ElementChangedEventHandler s_ElementChangedEventHandler;

    void show(const IDocument* pDoc, const ElementId& id, ElementChangedType type)
    {
        if (type == ElementChangedType::DeleteElement)
        {
            std::cout << StringUtils::toString(L"删除Id:") + StringUtils::toString(id.toValue()) << std::endl;
        }
        else
        {
            const IElement* pElement = pDoc->getElement(id);
            DBG_WARN_AND_RETURN_VOID_UNLESS(pElement && pElement->getElementId() == id, L"对象被修改，为什么不存在", L"蒋家伟", L"2023-12-20");
            const IElementBasicInfomation* pBasicInfo = pElement->getBasicInfomation();
            DBG_WARN_AND_RETURN_VOID_UNLESS(pBasicInfo, L"pBasicInfo为空", L"蒋家伟", L"2023-12-20");
            std::string prefixTips = StringUtils::toString(pBasicInfo->getName()) + StringUtils::toString(pBasicInfo->getDebugInfo());
            if (type == ElementChangedType::AddElement)
            {
                std::cout << prefixTips +  StringUtils::toString(L"添加Id:") + StringUtils::toString(id.toValue()) << std::endl;
            }
            else if (type == ElementChangedType::PreElementChanged)
            {
                std::cout << prefixTips + StringUtils::toString(L"预修改，fw调用 Id:") + StringUtils::toString(id.toValue()) << std::endl;
            }
            else if (type == ElementChangedType::PostElementChanged)
            {
                std::cout << prefixTips + StringUtils::toString(L"已修改, set调用 Id:") + StringUtils::toString(id.toValue()) << std::endl;
            }
            else
            {
                DBG_WARN_AND_RETURN_VOID_UNLESS(false, L"Element变化异常状态", L"蒋家伟", L"2023-12-20");
            }
        }
    }
}

jsdk::ElementChangedEventHandler::ElementChangedEventHandler()
{
    IElementChangedEvent::get()->registerHandler(this);
}

jsdk::ElementChangedEventHandler::~ElementChangedEventHandler()
{
    IElementChangedEvent::get()->unRegisterHandler(this);
}

void jsdk::ElementChangedEventHandler::On(const IArgs* pArgs)
{
    if (const IElementChangedEventArgs* pElementChangedEventArgs = quick_cast<IElementChangedEventArgs>(pArgs))
    {
        const ChangedStatusUMap& changedStatusUMap = pElementChangedEventArgs->getChangedMaps();
        // todo处理
        for (const auto& pair : changedStatusUMap)
        {
            show(pElementChangedEventArgs->getDocument(), pair.first, pair.second);
        }
    }
}
